package com.cakemallproject.controller;

import com.cakemallproject.pojo.mapperObj.Goods;
import com.cakemallproject.pojo.Result;
import com.cakemallproject.pojo.mapperObj.Type;
import com.cakemallproject.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping
    public Result list()  {
        log.info("获取商品列表");
        List<Goods> list = goodsService.list();
        return Result.success(list);
    }

    @PostMapping
    public Result insert(@RequestBody Goods goods) {
        log.info("添加商品：{}",goods);
        try {
            goodsService.insert(goods);
        } catch (RuntimeException e) {
            return Result.error("name_exist");
        }
        return Result.success();
    }


    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        goodsService.delete(ids);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Goods goods) {
        log.info("更新商品：{}",goods);
        try {
            goodsService.update(goods);
        } catch (RuntimeException e) {
            return Result.error("name_exist");
        }
        return Result.success();
    }

    @GetMapping("/search/{value}")
    public Result search(@PathVariable String value,
                         @RequestParam(required = false) List<Integer> filterTypes) {
        log.info("搜索商品：{},类型筛选：{}",value,filterTypes);
        if (filterTypes.isEmpty()) filterTypes = null;
        List<Goods> searchList = goodsService.search(value, filterTypes);
        return Result.success(searchList);
    }

    @GetMapping("/{tid}")
    public Result getByType(@PathVariable Integer tid) {
        List<Goods> list = goodsService.getByTid(tid);
        return Result.success(list);
    }

}
